package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.enums.InspectType;
import com.foreverwin.mes.lims.model.InspectPlan;
import com.foreverwin.mes.lims.model.InspectTask;
import com.foreverwin.mes.lims.service.InspectPlanService;
import com.foreverwin.mes.lims.service.InspectTaskService;
import com.foreverwin.mes.lims.util.DataValueConstant;
import com.foreverwin.mes.meapi.model.CustomFields;
import com.foreverwin.mes.meapi.model.Item;
import com.foreverwin.mes.meapi.model.Sfc;
import com.foreverwin.mes.meapi.service.CustomFieldsService;
import com.foreverwin.mes.meapi.service.ItemService;
import com.foreverwin.mes.meapi.service.SfcService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.InspectEndConfirmService;
import com.foreverwin.mes.lims.model.InspectEndConfirm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Levy
 * @since 2020-03-04
 */
@Controller
@RequestMapping("/inspectEndConfirms")
public class InspectEndConfirmController {
    private final Logger logger = LoggerFactory.getLogger(InspectEndConfirmController.class);

    @Autowired
    public InspectEndConfirmService inspectEndConfirmService;
    @Autowired
    public ItemService itemService;
    @Autowired
    public SfcService sfcService;
    @Autowired
    public InspectTaskService inspectTaskService;
    @Autowired
    InspectPlanService inspectPlanService;
    @Autowired
    CustomFieldsService customFieldsService;


    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getInspectEndConfirmById(@PathVariable String id) {
        InspectEndConfirm result;
        try {
            result = inspectEndConfirmService.selectById(id);
        } catch (Exception e) {
            logger.error("getInspectEndConfirmById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getInspectEndConfirmList(InspectEndConfirm inspectEndConfirm){
        List<InspectEndConfirm> result;
        try {
            EntityWrapper<InspectEndConfirm> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectEndConfirm);
            result = inspectEndConfirmService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectEndConfirmList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getInspectEndConfirmPageList")
    public AjaxResult getInspectEndConfirmPageList(FrontPage<InspectEndConfirm> frontPage, InspectEndConfirm inspectEndConfirm){
        Page result;
        try {
            String site = CommonMethods.getSite();
            inspectEndConfirm.setSite(site);
            EntityWrapper<InspectEndConfirm> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectEndConfirm);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("taskId", frontPage.getGlobalQuery())
                    .or().like("sfc", frontPage.getGlobalQuery())
                    .or().like("itemBo", frontPage.getGlobalQuery())
                    .or().like("finalResult", frontPage.getGlobalQuery())
                    .or().like("ncCode", frontPage.getGlobalQuery())
                    .or().like("createdUser", frontPage.getGlobalQuery())
                    .or().like("updatedUser", frontPage.getGlobalQuery())
        ;
            }
            result = inspectEndConfirmService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectEndConfirmPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param jsonObject  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult inspectEndConfirmSave(@RequestBody JSONObject jsonObject) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        //参数
        String taskNo = null;
        String sfc = null;
        String item = null;
        String pass = null;
        String ncCode = null;
        //Date now = new Date("");
        Date now = new Date();
        int count = 0;

        try {

            taskNo = (String)jsonObject.get("taskNo");
            sfc = (String)jsonObject.get("sfc");
            item = (String)jsonObject.get("item");
            pass = (String)jsonObject.get("pass");
            ncCode = (String)jsonObject.get("ncCode");

           /* List<Item> currentItemList = itemService.selectList(new EntityWrapper<Item>()
                    .eq("SITE", site)
                    .eq("ITEM", item)
                    .eq("CURRENT_REVISION", "true"));
            if (currentItemList == null || currentItemList.size() == 0) {
                throw BusinessException.build("物料【" + item + "】当前版本不存在");
            }
            Item currentItem = currentItemList.get(0);

           Sfc modelSfc = sfcService.selectById( StringUtils.genHandle( HandleBOConstants.SFC_BO , site , sfc ) );
           if ( modelSfc == null ) {
                throw BusinessException.build("检验批次【" + sfc + "】不存在");
            }

           if ( "fail".equals( pass ) ){
               //判断不良代码是否存在
           }*/

          InspectTask inspectTask = inspectTaskService.selectOne(
                   new EntityWrapper<InspectTask>()
                   .eq("TASK_ID",taskNo)
                   .eq("SITE",site) );
         if (  inspectTask == null  ){
             throw BusinessException.build("任务编号【"+ taskNo +"】不存在");
         }

           String handle = StringUtils.genHandle( HandleBOConstants.INSPECT_END_CONFIRM_BO ,site,taskNo );
           InspectEndConfirm oldModel = inspectEndConfirmService.selectById( handle );
           if ( oldModel == null ){
               InspectEndConfirm inspectEndConfirm = new InspectEndConfirm();
               inspectEndConfirm.setHandle( StringUtils.genHandle( HandleBOConstants.INSPECT_END_CONFIRM_BO ,site,taskNo ) );
               inspectEndConfirm.setSite( site );
               inspectEndConfirm.setTaskId( taskNo );
               inspectEndConfirm.setSfc( sfc );
               inspectEndConfirm.setFinalResult( pass );
               inspectEndConfirm.setItemBo( item );  //currentItem.getHandle()
               inspectEndConfirm.setNcCode( ncCode );
               inspectEndConfirm.setCreatedDateTime( now);
               inspectEndConfirm.setCreatedUser( user );
               count = inspectEndConfirmService.insert( inspectEndConfirm ) ? 1 : 0;

               //任务完成
               inspectTask.setTaskStatus( DataValueConstant.TASK_STATUS_COMPLETE );
               inspectTask.setEndTime( now );
               inspectTask.setUpdatedDateTime( now );
               inspectTask.setUpdatedUser( user );
               inspectTaskService.updateById( inspectTask );

               String type =  inspectTask.getInspectType();
               //外校任务完成时，改写设备自定义字段
               if (InspectType.OS.getCode().equals( type ) ){

                  String planBo =  inspectTask.getPlanBo();
                  InspectPlan inspectPlan = inspectPlanService.selectById( planBo );
                  String resrceBo = inspectPlan.getResrce();
                  customFieldsService.delete(
                          new EntityWrapper<CustomFields>()
                          .eq("HANDLE" ,resrceBo )
                          .eq( "ATTRIBUTE" ,DataValueConstant.RES_CALIBRATION_DATE )
                  );
                  CustomFields customFields = new CustomFields();
                  customFields.setAttribute( DataValueConstant.RES_CALIBRATION_DATE);
                  customFields.setHandle( resrceBo );
                  customFields.setValue( now.toString() );
                  customFields.setCreatedDateTime( now );
                  customFields.setModifiedDateTime( now );

                  customFieldsService.insert( customFields );
               }
           }

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }

        return AjaxResult.success(count == 0 ? "最终检验结果确认录入失败!" : "最终检验结果确认录入成功!");

    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult inspectEndConfirmDelete(@PathVariable("id") String id){
        int count;
        try {
            count = inspectEndConfirmService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectEndConfirmDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = inspectEndConfirmService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectEndConfirmBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }
}